﻿using DreamCMS.WebCore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.SessionState;

namespace DreamCMS.Web.common.tools
{
    /// <summary>
    /// verify 的摘要说明
    /// </summary>
    public class verify : IHttpHandler, IRequiresSessionState
    {
        private static byte[] randb = new byte[4];
        private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
        private Matrix m = new Matrix();
        private Bitmap charbmp = new Bitmap(30, 30);
        private Font[] fonts = new Font[]{
            new Font(new FontFamily("Times New Roman"),16+Next(3),FontStyle.Regular),
            new Font(new FontFamily("Georgia"),16+Next(3),FontStyle.Regular),
                new Font(new FontFamily("Arial"),16+Next(3),FontStyle.Regular),
                new Font(new FontFamily("Comic Sans MS"),16+Next(3),FontStyle.Regular)};
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/gif";
            CreateImage(GenerateCheckCode());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private static int Next(int max)
        {
            rand.GetBytes(randb);
            int value = BitConverter.ToInt32(randb, 0);
            value = value % (max + 1);
            if (value < 0)
            {
                value = -value;
            }
            return value;
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <returns></returns>
        private string GenerateCheckCode()
        {
            int number;
            string checkCode=ServerHelper.VerifyCode;
            if(!string.IsNullOrEmpty(checkCode))
            {
                return checkCode;
            }
            else
            {
                System.Random random=new Random();
                for(int i=0;i<4;i++)
                {
                    number=random.Next(10);
                    checkCode+=number.ToString();
                }
            }
            ServerHelper.VerifyCode = checkCode.ToLower();
            return checkCode;
        }

        private void CreateImage(string checkCode)
        { 
            if(checkCode==null || checkCode.Trim()==string.Empty)
            {
                return;
            }
            Bitmap img = new Bitmap((int)Math.Ceiling(checkCode.Length * 22.5),30);
            Graphics g = Graphics.FromImage(img);
            g.SmoothingMode = SmoothingMode.HighSpeed;
            g.Clear(Color.White);
            try
            {
                Random random = new Random(); //生成随机生成器
                for(int i=0;i<2;i++)
                {
                    int x1 = random.Next(img.Width);
                    int y1 = random.Next(img.Height);
                    int x2 = random.Next(img.Width);
                    int y2 = random.Next(img.Height);
                    g.DrawLine(new Pen(Color.Black), new Point(x1, y1), new Point(x2, y2));
                }
                Graphics charg = Graphics.FromImage(charbmp);
                SolidBrush drawBrush = new SolidBrush(Color.FromArgb(Next(100), Next(100), Next(100)));
                float charx = -18;
                for(int i=0;i<checkCode.Length;i++)
                {
                    m.Reset();
                    m.RotateAt(Next(30) - 25, new PointF(Next(3) + 7, Next(3) + 7));
                    charg.Clear(Color.Transparent);
                    charg.Transform = m;
                    drawBrush.Color = Color.Black;
                    charx = charx + 20 + Next(2);
                    PointF drawPoint = new PointF(charx, 0.1F);
                    charg.DrawString(checkCode[i].ToString(), fonts[Next(fonts.Length - 1)], drawBrush, new PointF(0, 0));
                    charg.ResetTransform();
                    g.DrawImage(charbmp, drawPoint);
                }
                for(int i=0;i<25;i++)
                {
                    int x = random.Next(img.Width);
                    int y = random.Next(img.Height);
                    img.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, ImageFormat.Gif);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                img.Dispose();
            }
        }
        
    }
}